package cn.kai.basic.service.impl;

import cn.kai.auth.domain.Logininfo;
import cn.kai.auth.mapper.LogininfoMapper;
import cn.kai.basic.constants.BaseConstant;
import cn.kai.basic.dto.LoginDto;
import cn.kai.basic.dto.WechatDto;
import cn.kai.basic.exception.BusinessException;
import cn.kai.basic.jwt.JwtUtils;
import cn.kai.basic.jwt.LoginResult;
import cn.kai.basic.jwt.RsaUtils;
import cn.kai.basic.service.ILoginService;
import cn.kai.basic.util.AjaxResult;
import cn.kai.basic.util.HttpClientUtils;
import cn.kai.basic.util.MD5Utils;
import cn.kai.basic.util.StrUtils;
import cn.kai.system.domain.Menu;
import cn.kai.system.mapper.MenuMapper;
import cn.kai.system.mapper.PermissionMapper;
import cn.kai.user.domain.User;
import cn.kai.user.domain.Wxuser;
import cn.kai.user.mapper.UserMapper;
import cn.kai.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.kai.basic.jwt.JwtUtils.generateTokenExpireInMinutes;
import static cn.kai.basic.jwt.JwtUtils.generateTokenExpireInSeconds;

/**
 * @Author Kai
 * @Date 2022/6/18 21:07
 * @PackageName:cn.kai.basic.service.impl
 * @ClassName: LoginServiceImpl
 * @Description: 登录接口实现类
 * @Version 1.0
 */

/**
 * 账号密码登录
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
//    1.数据空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new BusinessException("所有参数必须填！！");
        }
//    2.验证账号密码是否正确
//    2.1.根据前端传过来的username去数据库查数据，注意数据库应该应该要同时校验邮箱、电话、用户名，保证用户任意输入一个都能登录成功
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
//    2.1.1.如果查出来的数据不存在则表明该用户不存在。
        if (logininfo == null){
            throw new BusinessException("账户或密码错误!!!");
        }
//    2.1.2.查出来数据则校验密码是否正确
        if (!MD5Utils.encrypByMd5(dto.getPassword()+logininfo.getSalt()).equals(logininfo.getPassword())){
            throw new BusinessException("账户或密码错误!!!");
        }
//    3.将数据存入redis并设置过期时间30分钟
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//    4.生成uuid即token，将token和用户数据存入map中返回给前端（注意清空用户的敏感信息）
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //删除用户敏感信息
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
        return loginSuccessHandler(logininfo);
    }

    /**
     * 处理登录成功后的权限封装
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        //加密数据时需要载荷对象
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //当为员工登录时才进行权限的封装
        if (logininfo.getType() == 0){
            //登录成功
            //我们需要查询出当前登录人对应的菜单+按钮权限
            // 菜单权限
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            // 按钮权限
            List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }
        //把登录人信息 + 权限 加密封装成JWT串，返回给前端
        //使用私钥将数据加密生成jwt
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
        String jwtStr = generateTokenExpireInMinutes(loginResult, privateKey, 30);
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);
        //删除用户敏感信息
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("menus",loginResult.getMenus());
        map.put("permissions",loginResult.getPermissions());
        return map;
    }

    /**
     * 微信扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        //校验state是否一致,防止跨域攻击
        if (dto.getState() != 1){
            throw new BusinessException("滚!!!");
        }
//    1.1.接受到前端发送的code
        String code = dto.getCode();
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数不能为空！！！");
        }
//    1.2.向微信发请求通过code获得token和openid
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL
                    .replace("APPID", BaseConstant.WeChatConstants.APPID)
                    .replace("SECRET", BaseConstant.WeChatConstants.SECRET)
                    .replace("CODE", code);
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
//    1.3.通过openid去对应数据库表查询该用户是否曾经使用过微信登录
        Wxuser wxuser = wxuserMapper.loadByOpenid(openId);
//    1.3.1.有数据-使用过微信登录，直接免密登录
        if (wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
//    将数据存入redis并设置过期时间30分钟
            /*String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//    生成uuid即token，将token和用户数据存入map中返回给前端（注意清空用户的敏感信息）
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //删除用户敏感信息
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);*/
            return AjaxResult.me().setResultObj(loginSuccessHandler(logininfo));
        }
//    1.3.2.没有数据-说明未使用过微信登录返回token和openid给前端绑定页面，让用户绑定账户
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * 微信账户绑定
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binder(WechatDto dto) {
        if (StringUtils.isEmpty(dto.getPhone())
                        || StringUtils.isEmpty(dto.getPassword())
                        || StringUtils.isEmpty(dto.getAccessToken())
                        || StringUtils.isEmpty(dto.getOpenId())){
            throw new BusinessException("参数不能为空！！！");
        }
//        2.2.1.接受相关参数
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
//        2.2.2.去对应数据库表查询该手机号是否已经注册
        User user = userMapper.loadByPhone(phone);
//        2.2.2.1.数据存在，等待响应
        Logininfo logininfo = null;
        if (user != null){
            String passwordTemp = MD5Utils.encrypByMd5(dto.getPassword()+user.getSalt());
            //判断密码是否正确
            if (passwordTemp.equals(user.getPassword())){
                //判断该账户是否被其他微信绑定
                Wxuser wxuser = wxuserMapper.loadByUserId(user.getId());
                if (wxuser != null){
                    throw new BusinessException("该账户已被其他微信账户绑定，请更换账户！！！");
                }
                logininfo = logininfoMapper.loadByUserId(user.getId());
            }
            throw new BusinessException("该账户已存在，请确认是否是您自己的账户，如是请输入正确的密码！！！");
        }else {
//        2.2.2.2.不存在 生成新的t_user + t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
//        2.2.3.根据token + openid 去微信查询微信的用户基本信息
        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
//        2.2.4.根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
//        2.2.5.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//        2.2.6.保存t_wxuser
        wxuserMapper.save(wxuser);
//        2.2.7.直接免密登录
//    将数据存入redis并设置过期时间30分钟
        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//    生成uuid即token，将token和用户数据存入map中返回给前端（注意清空用户的敏感信息）
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //删除用户敏感信息
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
        return loginSuccessHandler(logininfo);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//注意：一定要手动设置type 前端用户注册  1
        return logininfo;
    }

    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
